package drds.binlog.client;

import drds.binlog.client.adapter.loader.AdapterLoader;
import drds.binlog.client.adapter.support.ClientConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;

public class Launcher//Launcher
{

    private static final String CLASSPATH_URL_PREFIX = "classpath:";
    private static final Logger logger = LoggerFactory.getLogger(Launcher.class);

    public static void main(String[] args)
    {
        try
        {
            logger.info("## set default uncaught exception handler");
            setGlobalUncaughtExceptionHandler();

            logger.info("## load canal client configurations");
            String conf = System.getProperty("client.conf", "classpath:canal-client.yml");
            ClientConfig clientConfig;
            if (conf.startsWith(CLASSPATH_URL_PREFIX))
            {
                conf = StringUtils.substringAfter(conf, CLASSPATH_URL_PREFIX);
                clientConfig = new Yaml().loadAs(Launcher.class.getClassLoader().getResourceAsStream(conf),
                        ClientConfig.class);
            } else
            {
                clientConfig = new Yaml().loadAs(new FileInputStream(conf), ClientConfig.class);
            }
            logger.info("## start the canal client adapters.");
            final AdapterLoader adapterLoader = new AdapterLoader(clientConfig);
            adapterLoader.init();
            logger.info("## the canal client adapters are running now ......");
            Runtime.getRuntime().addShutdownHook(new Thread()
            {

                public void run()
                {
                    try
                    {
                        logger.info("## stop the canal client adapters");
                        adapterLoader.destroy();
                    } catch (Throwable e)
                    {
                        logger.warn("## something goes wrong when stopping canal client adapters:", e);
                    } finally
                    {
                        logger.info("## canal client adapters are down.");
                    }
                }

            });
        } catch (Throwable e)
        {
            logger.error("## something goes wrong when starting up the canal client adapters:", e);
            System.exit(0);
        }
    }

    private static void setGlobalUncaughtExceptionHandler()
    {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
        {

            @Override
            public void uncaughtException(Thread t, Throwable e)
            {
                logger.error("UnCaughtException", e);
            }
        });
    }
}
